import navToNext from '../../wxjs/navToNext.js'
const app = getApp();
let methods = {
  setTime,
  setAward,
  
  awardScroll,
  cutAward,
  signUp,
  payment,
  invitation,

  toPayPage(e) {
    console.error(this.data)
    const pagesData = getCurrentPages()
    const currentPageDate = pagesData[pagesData.length - 1]
    console.error(currentPageDate)
    const that = this;
    // 判断用户登录
    var myInfo = app.isNavigateToLogin();
    if (!myInfo) return;
    myInfo = app.isNavigateToBind();
    if (!myInfo) return;
    const curItem = that.data.selfAwardParam
    wx.navigateTo({
      url: '/pages/pay/pay?MatchType=2&item=' + JSON.stringify(curItem)
    })
  },
};

var component = {
  properties: {
    rewardMold: String,
    selfAwardParam:{
      type: Object,
      observer: function (newVal) {
        // 倒计时
        const that=this;

        clearInterval(that.data.timeInterval);
        clearInterval(that.data.awardInterval);

        if (newVal.scheduleStatus == 0) {
          that.setAward(newVal.currentTimeStamp, newVal.startTimeStamp);
        }
        that.cutAward(true, '', newVal.bonusPool);
        if (newVal.bonusPool > 100) {
          that.awardScroll(2, 100, newVal.bonusPool);
        } else {
          that.awardScroll(1, 100, newVal.bonusPool);
        }
      }
    },
  },
  data: {
    joining: false, // true：正在报名中，false，相反
    xhx_images: app.xhx_images,
    xhx_route: app.xhx_route,
    
    awardShow: 0,
    timeTotal: { daysRound: '00', hoursRound: '00', minutesRound: '00', seconds: '00' },

    timeInterval: null,
    awardInterval:null,

    // status:2, //0:报名中；1：进行中；2：已结束
  },
  methods: Object.assign(navToNext, methods)
};

Component(component);

// 时间倒计时
function setTime(my_time) {
  var that = this;
  var days = my_time / 1000 / 60 / 60 / 24;
  var daysRound = Math.floor(days);
  var hours = my_time / 1000 / 60 / 60 - (24 * daysRound);
  var hoursRound = Math.floor(hours);
  var minutes = my_time / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
  var minutesRound = Math.floor(minutes);
  var seconds = my_time / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
  var time = { daysRound: daysRound, hoursRound: hoursRound, minutesRound: minutesRound, seconds: seconds }
  that.setData({
    timeTotal: time
  })
}
function setAward(curTime, startTime) {
  var that = this;
  var dateCur = curTime;
  var dateStart = startTime;
  // console.log(dateCur, '=================', dateStart)
  var my_time = dateStart - dateCur;
  // console.log('my_time=================', my_time)
  that.data.timeInterval = setInterval(function () {
    if (my_time == 0) {
      clearInterval(that.data.timeInterval);
    } else {
      my_time = my_time - 1000;
      that.setTime(my_time);
    }
  }, 1000);
}

// 奖金池滚动
function awardScroll(seconds, interval, moneyTotal) {
  var that = this;
  var award = moneyTotal;
  award = parseInt(award.toFixed(2) * 100);
  var awardShow = 0;
  seconds = seconds * 1000;
  var pre = award / (seconds / interval);
  if (pre <= 0.01) {
    return;
  } else {
    pre = Math.ceil(pre * 100) / 100;
  }

  that.data.awardInterval = setInterval(function () {
    if (seconds == 0) {
      clearInterval(that.data.awardInterval);
    } else {
      awardShow = awardShow + pre;
      if (awardShow + pre > award) {
        awardShow = award;
      }
      award = Math.ceil(award);
      that.cutAward(false, awardShow, award);
      seconds = seconds - interval;
    }
  }, interval);
}
// 切割奖金池
function cutAward(first, moneyList, award) {
  var that = this;
  var length = (award).toString().length;;
  if ((award.toString()).indexOf(".") != -1) {
    length = length - 1;
  }
  var awardShow = [];
  if (first) {
    if (award <= 0.01) {
      return;
    }

    for (let i = 0; i < length; i++) {
      awardShow[i] = 0;
    }
  } else {
    var moneyArr = (moneyList / 100).toFixed(2);
    moneyArr = moneyArr.split('');
    awardShow = moneyArr;
    var num = length - moneyArr.length;
    if (num > 0) {
      for (var i = 0; i < num; i++) {
        moneyArr.unshift(0);
      }
    }
  }
  // awardShow.splice(awardShow.length - 2, 0, '.');
  that.setData({
    awardShow: awardShow
  })
}

// 支付
function signUp(e) {
  // 正在参加中
  if (this.data.joining) {
    return
  } else {
    this.setData({
      joining: true
    })
  }

  const that = this;
  var challengeId = e.target.dataset.id;
  let totalPrice = e.target.dataset.price || 0;
  if (totalPrice == 0 || !challengeId) return false;
  // 判断用户登录
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;
  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  var payParam = {};
  payParam.tV2CustomMatchScheduleId = challengeId;
  payParam.wxMold = 1;

  app.middleware.requestAjax({
    serAddr: app.serAddrs.selfOrderByWXPay,
    data: payParam,
    cancelToast: true,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    success: function (ores) {
      that.payment(ores.data, challengeId);
    },
    fail: function (res) {
      that.setData({
        joining: false
      })
      app.middleware.showToast(res && res.msg || "请求失败");
    }
  })
}

function payment(data, challengeId) {
  const that = this;
  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.prepayId,
    signType: data.signType,
    paySign: data.paySign,
    success(res) {
      // that.getDetail();
      that.triggerEvent('myevent', { payBtn: true });
      that.setData({
        joining: false
      })
    },
    fail(res) {
      app.middleware.showToast("支付失败");
      that.setData({
        joining: false
      })
    },
    complete: function (res) {

    }
  })
}

function invitation(){
  this.triggerEvent('myevent', { payBtn: false });
}